<template>
    <div>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/goods' }">商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>商品列表</el-breadcrumb-item>
      </el-breadcrumb>


<!--      卡片区域-->
      <el-card>
        <el-alert
          title="添加商品信息"
          type="info"
          show-icon  center :closable="false">
        </el-alert>

<!--        步骤条-->
        <el-steps :active="active - 0" finish-status="success" space="240px" align-center>
          <el-step title="基本信息"></el-step>
          <el-step title="商品参数"></el-step>
          <el-step title="商品属性"></el-step>
          <el-step title="商品图片"></el-step>
          <el-step title="商品内容"></el-step>
          <el-step title="完成"></el-step>
        </el-steps>


<!--        tab切换栏-->
        <el-form :model="goodsdata" :rules="goodsdatarules" ref="goodsdataruleForm" label-width="100px" class="demo-ruleForm" label-position="top">
          <el-tabs :tab-position="tabPosition" v-model="active" :before-leave="rejiecttab" @tab-click="tab_click">
            <el-tab-pane label="基本信息" name="0">
                  <el-form-item label="商品名称" prop="goods_name">
                    <el-input v-model="goodsdata.goods_name"></el-input>
                  </el-form-item>
                  <el-form-item label="商品价格" prop="goods_price">
                    <el-input v-model="goodsdata.goods_price"></el-input>
                  </el-form-item>
                  <el-form-item label="商品重量" prop="goods_weight">
                    <el-input v-model="goodsdata.goods_weight"></el-input>
                  </el-form-item>
                  <el-form-item label="商品数量" prop="goods_number">
                    <el-input v-model="goodsdata.goods_number"></el-input>
                  </el-form-item>
                  <el-form-item label="商品分类" prop="goods_cat">
                    <el-cascader
                      v-model="goodsdata.goods_cat"
                      :options="goodsclassifydata"
                      @change="goodshandleChange" :props="goodsprops" clearable></el-cascader>
                  </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品参数" name="1">
              <el-form-item :label="item.attr_name" v-for="item in dt_cs" :key="item.attr_id" >
                <el-checkbox-group v-model="item.attr_vals" >
                  <el-checkbox  border :label="item2"  v-for="(item2,index) in item.attr_vals" :key="index"></el-checkbox>
                </el-checkbox-group >
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品属性" name="2">
              <el-form-item :label="item.attr_name" v-for="item in jt_cs" :key="item.attr_id" >
                  <el-input v-model="item.attr_vals"></el-input>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品图片" name="3">
              <el-upload
                class="upload-demo"
                :action="picture"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                list-type="picture" :on-error="fileerror" :headers="headerspicture" :on-success="handlesuccess">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-tab-pane>
            <el-tab-pane label="商品内容" name="4">
              <quill-editor v-model="goodsdata.goods_introduce"> </quill-editor>
              <el-button type="primary" class="addbtn" @click="addgoods">添加商品</el-button>
            </el-tab-pane>
          </el-tabs>
        </el-form>


<!--        缩略图的对话框-->
        <el-dialog
          title="图片缩略图"
          :visible.sync="imgdialogVisible"
          width="50%">
          <img :src="img_url" alt="" class="onimg">
          <span slot="footer" class="dialog-footer">
      <el-button @click="imgdialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="imgdialogVisible = false">确 定</el-button>
  </span>
        </el-dialog>

      </el-card>
    </div>
</template>

<script>
import _ from 'lodash'
export default {
    data() {
      return {
        active: '0',  // 步骤条的控制进度
        tabPosition: 'left', //tab切换栏的显示位置
        // 要提交的商品数据
        goodsdata: {
          goods_name: '', // 商品名称
          goods_cat: '', // 分类列表
          goods_price: '', // 商品价格
          goods_number: '', // 数量
          goods_weight: '', // 重量
          goods_introduce: '', // 介绍
          pics: [], // 上传图片的路径(对象)
          attrs: [] // 商品的参数
        },
        // 商品数据验证规则
        goodsdatarules: {
          goods_name: [
            { required: true, message: '请输入商品名称', trigger: 'blur' }
          ],
          goods_price: [
            { required: true, message: '请输入商品价格', trigger: 'blur' }
          ],
          goods_weight: [
            { required: true, message: '请输入商品重量', trigger: 'blur' }
          ],
          goods_number: [
            { required: true, message: '请输入商品数量', trigger: 'blur' }
          ],
          goods_cat: [
            { required: true, message: '请选择商品分类', trigger: 'blur' }
          ]
        },
        // 存储后台商品分类的数据
        goodsclassifydata: [],
        // 分类选择器的配置
        goodsprops: {
          label: 'cat_name', // 显示的分类名字
          children: 'children', // 分类的儿子
          value: 'cat_id'  // 选中的属性值
      },
        dt_cs: [],  // 存储动态参数
        jt_cs: [], // 存储静态属性
        // 图片上传的url地址
        picture: 'http://127.0.0.1:8888/api/private/v1/upload',
        // 图片的请求头
        headerspicture: {
          Authorization: window.sessionStorage.getItem('token')
        },
        img_url: '',  // 图片缩略图的url地址
        imgdialogVisible: false, // 缩略图的对话框判断
      }
    },
  created() {
      // 调用获取商品分类的函数
    this.getgoodslist()
  },
  methods: {
      async getgoodslist() {
          const {data: res} = await this.$http.get(`categories`)
        if (res.meta.status !== 200) return this.$message.error('获取分类数据失败，请重新进入，或者刷新页面')
        this.goodsclassifydata = res.data
      },
    goodshandleChange(a) {  // 选择商品分类触发
      if (a.length !== 3) {
        this.goodsdata.goods_cat = []
      }
    },
    rejiecttab(a,b) {
      if (this.goodsdata.goods_cat.length !== 3) {
        this.$message.error('请填分类')
        return false
      }
    },
    async tab_click() {
      console.log(this.active)
        if (this.active === '1') {
          const {data: res} = await this.$http.get(`categories/${this.cateID}/attributes`,{
            params: {sel: 'many'}})
          if (res.meta.status !== 200) return this.$message.error('获取动态参数失败')
          res.data.forEach(item => {
            item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(',')
          })
          this.dt_cs = res.data
        }
        if (this.active === '2') {
          const {data: res} = await this.$http.get(`categories/${this.cateID}/attributes`,{
            params: {sel: 'only'}})
          if (res.meta.status !== 200) return this.$message.error('获取静态属性失败')
          res.data.forEach(item => {
            item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(',')
          })
          this.jt_cs = res.data
        }
      },
    handlePreview(response) {  // 商品的缩略图打开
      this.img_url = response.response.data.url
      this.imgdialogVisible = true
    },
    handleRemove(file) {  // 清除商品图片
      const file_path = file.response.data.tmp_path
      const index = this.goodsdata.pics.findIndex(x => {
        return x.pics === file_path
      })
      this.goodsdata.pics.splice(index,1)
    },
    handlesuccess(response) {  // 图片上传成功
      this.$message.success('图片上传成功')
      const pic_url = {
        pics: response.data.tmp_path
      }
      this.goodsdata.pics.push(pic_url)
    },
    fileerror() {
      this.$message.error('图片上传失败')
    },
    addgoods() {
      this.$refs.goodsdataruleForm.validate(async valid => {
        if (valid) {
          // 拷贝新的表单
          let form = _.cloneDeep(this.goodsdata)
          form.goods_cat = form.goods_cat.join(',')
          // 解决动态参数
          this.dt_cs.forEach(item => {
            const datainfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_value
            }
            form.attrs.push(datainfo)
          })
          // 解决静态参数问题
          this.jt_cs.forEach(item => {
            const jtdatainfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_value
            }
            form.attrs.push(jtdatainfo)
          })
          const {data: res} = await this.$http.post(`goods`,form)
          if (res.meta.status !== 201) return this.$message.error('添加商品失败')
          this.$message.success('成功添加了商品')
          this.$router.push('/goods')
        } else {
          this.$message.error('请填写必要的表单项')
          return false;
        }
      });
    }
    },
  computed: {
      cateID() {
        if (this.goodsdata.goods_cat.length === 3) {
          return this.goodsdata.goods_cat[2]
        }
        return null
    }
  }

}
</script>

<style scoped>
.el-breadcrumb {
  margin: 0 0 15px 15px;
}
.el-pagination {
  margin-top: 10px;
}
.el-steps {
  margin-top: 10px;
  margin-bottom: 20px;
}
.el-tabs {
  margin-top: 20px;
}
.el-checkbox.is-bordered.is-checked {
  margin: 0 5px 0 0 !important;
}
.onimg {
  width: 100%;
  overflow: hidden;
}
.addbtn {
  margin-top: 20px;

}
</style>
